import random
import pygame
from queue import PriorityQueue

# 初始化窗口参数
WIDTH = 600
WIN = pygame.display.set_mode((WIDTH, WIDTH))
pygame.display.set_caption("A*路径搜索可视化演示,Enter开始搜索,C清空地图")

# 定义颜色
RED = (255, 0, 0)         # 关闭节点
GREEN = (0, 255, 0)       # 已经走过路径
BLUE = (0, 255, 255)      # 开启节点
YELLOW = (255, 255, 0)    # 起点
WHITE = (255, 255, 255)   # 空格子
BLACK = (0, 0, 0)         # 障碍物
PURPLE = (128, 0, 128)    # 路径
ORANGE = (255, 165 ,0)    # 起点
TURQUOISE = (64, 224, 208)# 终点

# 定义每个格子的节点
class Spot:
    def __init__(self, row, col, width, total_rows):
        self.row = row
        self.col = col
        self.x = row * width
        self.y = col * width
        self.color = WHITE
        self.neighbors = []
        self.width = width
        self.total_rows = total_rows

    def get_pos(self):
        return self.row, self.col

    def is_closed(self):
        return self.color == RED

    def is_open(self):
        return self.color == GREEN

    def is_barrier(self):
        return self.color == BLACK

    def is_start(self):
        return self.color == ORANGE

    def is_end(self):
        return self.color == TURQUOISE

    def reset(self):
        self.color = WHITE

    def make_start(self):
        self.color = ORANGE

    def make_closed(self):
        self.color = RED

    def make_open(self):
        self.color = GREEN

    def make_barrier(self):
        self.color = BLACK

    def make_end(self):
        self.color = TURQUOISE

    def make_path(self):
        self.color = PURPLE

    def draw(self, win):
        pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.width))

    def update_neighbors(self, grid):
        self.neighbors = []
        # 四方向移动，上、下、左、右
        if self.row < self.total_rows - 1 and not grid[self.row + 1][self.col].is_barrier():
            self.neighbors.append(grid[self.row + 1][self.col])

        if self.row > 0 and not grid[self.row - 1][self.col].is_barrier():
            self.neighbors.append(grid[self.row - 1][self.col])

        if self.col < self.total_rows - 1 and not grid[self.row][self.col + 1].is_barrier():
            self.neighbors.append(grid[self.row][self.col + 1])

        if self.col > 0 and not grid[self.row][self.col - 1].is_barrier():
            self.neighbors.append(grid[self.row][self.col - 1])

# 曼哈顿距离
def h(p1, p2):
    x1, y1 = p1
    x2, y2 = p2
    return abs(x1 - x2) + abs(y1 - y2)

# 画网格
def make_grid(rows, width):
    grid = []
    gap = width // rows  # 每个格子的大小
    for i in range(rows):
        grid.append([])
        for j in range(rows):
            spot = Spot(i, j, gap, rows)
            grid[i].append(spot)
    return grid

def draw_grid(win, rows, width):
    gap = width // rows
    for i in range(rows):
        pygame.draw.line(win, (128, 128, 128), (0, i * gap), (width, i * gap))
        for j in range(rows):
            pygame.draw.line(win, (128, 128, 128), (j * gap, 0), (j * gap, width))

def draw(win, grid, rows, width):
    win.fill(WHITE)

    for row in grid:
        for spot in row:
            spot.draw(win)

    draw_grid(win, rows, width)
    pygame.display.update()

# 返回点击的位置
def get_clicked_pos(pos, rows, width):
    gap = width // rows
    y, x = pos

    row = y // gap
    col = x // gap

    return row, col

# 回溯路径
def reconstruct_path(came_from, current, draw):
    while current in came_from:
        current = came_from[current]
        current.make_path()
        draw()

# A*搜索算法
def algorithm(draw, grid, start, end):
    count = 0
    open_set = PriorityQueue()
    open_set.put((0, count, start))
    came_from = {}

    g_score = {spot: float("inf") for row in grid for spot in row}
    g_score[start] = 0
    f_score = {spot: float("inf") for row in grid for spot in row}
    f_score[start] = h(start.get_pos(), end.get_pos())

    open_set_hash = {start}

    while not open_set.empty():
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()

        current = open_set.get()[2]
        open_set_hash.remove(current)

        if current == end:
            reconstruct_path(came_from, end, draw)
            end.make_end()
            start.make_start()
            return True

        for neighbor in current.neighbors:
            temp_g_score = g_score[current] + 1

            if temp_g_score < g_score[neighbor]:
                came_from[neighbor] = current
                g_score[neighbor] = temp_g_score
                f_score[neighbor] = temp_g_score + h(neighbor.get_pos(), end.get_pos())
                if neighbor not in open_set_hash:
                    count += 1
                    open_set.put((f_score[neighbor], count, neighbor))
                    open_set_hash.add(neighbor)
                    neighbor.make_open()

        draw()

        if current != start:
            current.make_closed()

    return False


# 自动生成障碍、起点、终点
def init_map(grid, rows):
    total_cells = rows * rows
    num_barriers = int(total_cells * 0.25)  # 25%的障碍物

    # 随机设置障碍物
    for _ in range(num_barriers):
        row = random.randint(0, rows - 1)
        col = random.randint(0, rows - 1)
        grid[row][col].make_barrier()

    # 随机设置起点和终点，确保不是障碍物
    while True:
        start_row = random.randint(0, rows - 1)
        start_col = random.randint(0, rows - 1)
        if not grid[start_row][start_col].is_barrier():
            start = grid[start_row][start_col]
            start.make_start()
            break

    while True:
        end_row = random.randint(0, rows - 1)
        end_col = random.randint(0, rows - 1)
        if not grid[end_row][end_col].is_barrier() and (
            end_row != start_row or end_col != start_col
        ):
            end = grid[end_row][end_col]
            end.make_end()
            break

    return start, end


# 主程序
def main(win, width):
    ROWS = 50
    grid = make_grid(ROWS, width)


    start, end = init_map(grid, ROWS)

    run = True
    started = False
    while run:
        draw(win, grid, ROWS, width)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                    run = False
                    pygame.quit()
                if event.key == pygame.K_c:
                    start, end = init_map(grid, ROWS)
                    started = False
            if not started and event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    for row in grid:
                        for spot in row:
                            spot.update_neighbors(grid)

                    algorithm(lambda: draw(win, grid, ROWS, width), grid, start, end)
                    started = True

                if event.key == pygame.K_c:
                    start, end = init_map(grid, ROWS)

                    started = False
    pygame.quit()


if __name__ == "__main__":
        main(WIN, WIDTH)
